﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Savage.DotNetLibrary.DatabaseLibrary
{
    public class Users
    {
        public Users(string connectionString)
        {
            _sqlDataWrapper = new SqlDataWrapper(connectionString);
        }

        private SqlDataWrapper _sqlDataWrapper;

        /// <summary>
        /// Adds a user to the current database.
        /// </summary>
        /// <param name="userName">The name by which the user is identified inside this database.</param>
        public void CreateUser(string userName)
        {
            CreateUser(userName, userName);
        }

        /// <summary>
        /// Adds a user to the current database.
        /// </summary>
        /// <param name="userName">The name by which the user is identified inside this database.</param>
        /// <param name="loginName">The SQL Server login for which the database user is being created. login_name must be a valid login in the server. When this SQL Server login enters the database it will acquire the name and ID of the database user that is being created.</param>
        public void CreateUser(string userName, string loginName)
        {
            if (userName == null)
                throw new ArgumentNullException("userName");

            //Escape and trim the roleName
            userName = userName.Trim().Replace("]", "]]");
            if (!String.IsNullOrEmpty(loginName))
                loginName = loginName.Replace("]", "]]");

            //Build the sql
            string cmdText = String.Format(CultureInfo.InvariantCulture, "CREATE USER [{0}]", userName);
            if (!String.IsNullOrEmpty(loginName))
                cmdText += String.Format(CultureInfo.InvariantCulture, " FOR LOGIN [{0}]", loginName);

            _sqlDataWrapper.ExecuteNonQuery(cmdText);
        }

        /// <summary>
        /// Removes a user from the current database.
        /// </summary>
        /// <param name="userName">The name by which the user is identified inside this database.</param>
        public void DropUser(string userName)
        {
            if (userName == null)
                throw new ArgumentNullException("userName");

            //Escape and trim the roleName
            userName = userName.Trim().Replace("]", "]]");

            //Build the sql
            string cmdText = String.Format(CultureInfo.InvariantCulture, "DROP USER [{0}]", userName);

            _sqlDataWrapper.ExecuteNonQuery(cmdText);
        }
    }
}
